package com.chc.web.reader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chc.web.borrow.entity.BorrowParm;
import com.chc.web.reader.entity.Reader;
import com.chc.web.reader.entity.ReaderParm;
import com.chc.web.reader.mapper.ReaderMapper;
import com.chc.web.reader.service.ReaderService;
import com.chc.web.reader_role.entity.ReaderRole;
import com.chc.web.reader_role.mapper.ReaderRoleMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/04/21/21:50
 * @Description:
 */
@Service
public class ReaderServiceImpl extends ServiceImpl<ReaderMapper, Reader> implements ReaderService {

    @Autowired
    private ReaderRoleMapper readerRoleMapper;

    @Override
    @Transactional
    public boolean saveReader(Reader reader) {
        //保存读者信息
        this.baseMapper.insert(reader);
        //维护角色列表
        ReaderRole readerRole = new ReaderRole();
        readerRole.setRoleId(reader.getRoleId());
        readerRole.setUserId(reader.getId());
        readerRoleMapper.insert(readerRole);
        return false;
    }

    @Override
    public IPage<Reader> list(ReaderParm parm) {

        QueryWrapper<Reader> query = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(parm.getName())){
            query.lambda().like(Reader::getName,parm.getName());
        }
        if (StringUtils.isNotEmpty(parm.getTel())){
            query.lambda().like(Reader::getTel,parm.getTel());
        }
        if (StringUtils.isNotEmpty(String.valueOf(parm.getCardid()))){
            query.lambda().like(Reader::getCardid,parm.getCardid());
        }
        //构造分页条件
        IPage<Reader> page = new Page<>();
        page.setSize(parm.getPageSize());
        page.setCurrent(parm.getCurrentPage());
        return this.baseMapper.selectPage(page,query);
    }

    @Override
    public Reader loadUser(String username) {
        //构造条件
        QueryWrapper<Reader> query = new QueryWrapper<>();
        query.lambda().eq(Reader::getUsername,username);
        return this.baseMapper.selectOne(query);
    }

    @Override
    public IPage<ReaderParm> getReaderList(ReaderParm parm) {
        //构造分页对象
        IPage<ReaderParm> page = new Page<>();
        page.setCurrent(parm.getCurrentPage());
        page.setSize(parm.getPageSize());
        return this.baseMapper.getReaderList(page,Long.valueOf(parm.getCardid()),parm.getName(),parm.getTel());
    }

}
